<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="实训入口" name="first">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button @click="handleChangeType(dict)" round :type="queryParams.type==dict.value ? 'primary' : ''" v-for="dict in dict.type.edu_training_type" :key="dict.value">{{ dict.label }}</el-button>
          </el-col>
          <el-button type="primary" @click="handleAdd" style="float: right; margin-right: 6px;">创建</el-button>
        </el-row>
        <div v-show="total == 0" style="padding: 80px 0;"><el-empty description="暂无实训"></el-empty></div>
        <el-row justify="space-between" :gutter="40">
          <el-col class="panel-col" v-for="(item, index) in list" :key="index" :xs="12" :sm="12" :lg="6">
            <el-card :body-style="{ padding: '0px' }">
              <div class="box"  @mouseenter="showIndex = index" @mouseleave="showIndex = undefined">
                <div class="opt" v-show="showIndex == index">
                  <el-button type="primary" icon="el-icon-edit" circle @click="handleUpdate(item)"></el-button>
                  <el-button type="danger" icon="el-icon-delete" circle @click="handleDelete(item)"></el-button>
                </div>
                <img :src="item.cover ? item.cover : coverImg" class="image">
                <div style="padding: 14px;">
                  <span>{{ item.name }}</span>
                  <div class="bottom">
                    <span class="teacher">实训时间:{{ parseTime(item.startDate, '{y}-{m}-{d}') }} / {{ parseTime(item.endDate, '{y}-{m}-{d}') }}</span>
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
      <div style="height: 600px; overflow: auto;">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="环境名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入环境名称" />
          </el-form-item>
          <el-form-item label="环境类型" prop="type">
            <el-select v-model="form.type" placeholder="环境类型" size="small">
              <el-option
                v-for="dict in dict.type.edu_training_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="实训时长" prop="times">
            <el-select v-model="form.times" placeholder="实训时长" size="small">
              <el-option
                v-for="dict in times"
                :key="dict"
                :label="formatTime(dict)"
                :value="dict"
              />
            </el-select>
            <div>设置默认实训时长，实训剩余时长为0时，实训将自动退出</div>
          </el-form-item>
          <el-form-item label="分配用户" prop="users">
            <el-transfer :data="userList" v-model="users" :titles="titles"
              :props="{
                key: 'userId',
                label: 'userName'
              }" 
              filterable
              :filter-method="filterMethod"
              filter-placeholder="请输入姓名"></el-transfer>
          </el-form-item>
          <el-form-item label="开始时间" prop="startDate">
            <el-date-picker
              v-model="form.startDate"
              type="datetime"
              placeholder="选择开始时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="endDate">
            <el-date-picker
              v-model="form.endDate"
              type="datetime"
              placeholder="选择结束时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="排序编号" prop="sort">
            <el-input v-model="form.sort" placeholder="请输入排序编号" />
          </el-form-item>
          <el-form-item label="环境封面" prop="cover">
            <ImageUpload :limit="1" :fileSize="2" @input="handleUploadSuccess"/>
          </el-form-item>
        </el-form>
      </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTraining, getTraining, addTraining, updateTraining, delTraining } from "@/api/edu/training";
import { listUser } from "@/api/system/user";
import coverImg from '@/assets/images/vnc_default_cover.png'
export default {
  name: "CourseType",
  dicts: ['sys_bool_status','edu_training_type'],
  data() {
    return {
      coverImg: coverImg,
      showIndex: undefined,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      activeName: "first",
      typeList: [],
      userList: [],
      users: [],
      titles: ["未添加用户", "已添加用户"],
      fileType: ['png', 'jpg', 'jpeg'],
      times: [1800, 2700, 3600, 5400, 7200, 14400, 21600, 28800, 43200],
      // 查询参数
      queryParams: {
        page: 1,
        limit: 20,
        type: 0
      },
      // 表单参数
      form: {
        id: undefined,
        name: undefined,
        type: undefined,
        imageId: undefined,
        imageName: undefined,
        times: undefined,
        users: undefined,
        sort: undefined,
        startDate: undefined,
        endDate: undefined,
        cover: undefined
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "环境名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "环境类型不能为空", trigger: "blur" }
        ],
        times: [
          { required: true, message: "实训时长不能为空", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getUserList();
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listTraining(this.queryParams).then(response => {
        this.list = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getUserList(){
      listUser({pageNum: 1, pageSize: 1000}).then(response => {
        this.userList = response.rows;
      });
    },
    filterMethod(query, item){
      return item.userName.indexOf(query) > -1;
    },
    formatTime(t){
      return (t / 60) + '分钟';
    },
    handleChangeType(item){
      if(item){
        this.queryParams.type = item.value;
      } else {
        this.queryParams.type = undefined;
      }
      this.handleQuery();
    },
    handleClick(){},
    handleUploadSuccess(data){
      this.form.cover = data;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        type: undefined,
        imageId: undefined,
        imageName: undefined,
        times: undefined,
        users: undefined,
        sort: undefined,
        startDate: undefined,
        endDate: undefined,
        cover: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.postId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加实训";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getTraining(row.id).then(response => {
        this.form = response.data;
        this.form.type = this.form.type + '';
        this.users = JSON.parse(this.form.users)
        this.open = true;
        this.title = "修改实训";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.users = JSON.stringify(this.users);
          if (this.form.id != undefined) {
            updateTraining(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTraining(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delTraining(row.id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    }
    
  }
};
</script>
<style scoped lang="scss">
  .mb8{
    padding: 10px 0;
  }
  .panel-col{
    padding-bottom: 20px;
  }
  .teacher {
    font-size: 13px;
    color: #999;
  }
  .bottom{
    margin-top: 10px;
  }
  .box{
    position: relative;
  }
  .opt{
    position: absolute;
    top: 10px;
    right: 20px;
  }
  .image {
    width: 100%;
    display: block;
  }
</style>